<?php namespace Phpcmf\Controllers\Admin;

// 草稿箱
class Content extends \Phpcmf\Table
{
    private $tid;

    public function __construct()
    {
        parent::__construct();
        // 支持附表存储
        $this->is_data = 0;
        // 表单显示名称
        $this->name = dr_lang('内容库');
        // 字段划分
        $j = 0;
        $field = [];
        for ($i = 1; $i<=9; $i++) {
            $field['title_'.$i] = array(
                'ismain' => 0,
                'displayorder' => $j,
                'name' => dr_lang('标题'),
                'fieldname' => 'title_'.$i,
                'fieldtype' => 'Text',
                'setting' => array(
                    'option' => array(
                        'width' => '100%',
                    ),
                    'validate' => array(
                        'formattr' => ' onblur="dr_wx_show_title('.$i.');"',
                    )
                )
            );
            $j++;
            $field['author_'.$i] = array(
                'ismain' => 0,
                'displayorder' => $j,
                'name' => dr_lang('作者'),
                'fieldname' => 'author_'.$i,
                'fieldtype' => 'Text',
                'setting' => array(
                    'option' => array(
                        'width' => 200,
                    )
                )
            );
            $j++;
            $field['thumb_'.$i] = array(
                'ismain' => 0,
                'displayorder' => $j,
                'name' => dr_lang('封面'),
                'fieldtype' => 'File',
                'fieldname' => 'thumb_'.$i,
                'setting' => array(
                    'option' => array(
                        'ext' => 'jpg,png,jpeg,gif',
                        'size' => 20,
                    ),
                )
            );
            $j++;
            $field['description_'.$i] = array(
                'ismain' => 0,
                'displayorder' => $j,
                'name' => dr_lang('描述'),
                'fieldname' => 'description_'.$i,
                'fieldtype'	=> 'Textarea',
                'setting' => array(
                    'option' => array(
                        'width' => '90%',
                        'height' => 70,
                    ),
                    'validate' => array(
                        'xss' => 1,
                    ),
                )
            );
            $j++;
            $field['content_'.$i] = array(
                'ismain' => 0,
                'displayorder' => $j,
                'name' => dr_lang('内容'),
                'fieldtype' => 'Ueditor',
                'fieldname' => 'content_'.$i,
                'setting' => array(
                    'option' => array(
                        'mode' => 1,
                        'height' => 300,
                        'width' => '100%',
                        'mini' => 1,
                    ),
                    'validate' => [
                        'tips' => '内容中的图片一定不要太大，否则无法同步到微信服务器'
                    ]
                )
            );
            $j++;
            $field['url_'.$i] = array(
                'ismain' => 0,
                'displayorder' => $j,
                'name' => dr_lang('原文地址'),
                'fieldname' => 'url_'.$i,
                'fieldtype' => 'Text',
                'setting' => array(
                    'option' => array(
                        'width' => '100%',
                    )
                )
            );
        }
        // 初始化数据表
        $this->_init([
            'table' => weixin_wxtable('content'),
            'field' => $field,
            'order_by' => 'inputtime desc',
            'date_field' => 'inputtime',
        ]);
        \Phpcmf\Service::V()->assign([
            'menu' => \Phpcmf\Service::M('auth')->_admin_menu(
                [
                    '内容库' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/index', 'fa fa-th-list'],
                    '添加' => [''.APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/add', 'fa fa-plus'],
                    '修改' => ['hide:'.APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/edit', 'fa fa-plus'],
                    '清空附件media_id' => ['ajax:'.APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/clear_del', 'fa fa-file'],
                ]
            ),
            'myfieldinfo' => $field,
            'zt' => [
                0 => '发布成功',
                1 => '发布中',
                2 => '原创失败',
                3 => '常规失败',
                4 => '平台审核不通过',
                5 => '成功后用户删除所有文章',
                6 => '成功后系统封禁所有文章',
            ]
        ]);
    }

    public function clear_del() {
        \Phpcmf\Service::M()->table(weixin_wxtable('media_id'))->clear_all();
        $this->_json(1, '全部附件media_id记录被清空');
    }

    public function index() {
        $where = (string)$_GET['keyword'] ? '`title` LIKE "%'.$_GET['keyword'].'%"' : '';
        \Phpcmf\Service::M()->set_where_list($where);
        list($tpl) = $this->_list();
        \Phpcmf\Service::V()->display($tpl);
    }

    public function add() {
        list($tpl) = $this->_Post();
        \Phpcmf\Service::V()->display($tpl);
    }

    public function edit() {
        list($tpl) = $this->_Post(intval(\Phpcmf\Service::L('Input')->get('id')));
        \Phpcmf\Service::V()->display($tpl);
    }

    // 转存素材库
    public function module_add() {

        $mid = dr_safe_filename($_GET['mid']);
        $row = \Phpcmf\Service::M('Module')->table('module')->where('dirname', $mid)->getRow();
        if (!$row) {
            $this->_json(0, dr_lang('此模块[%s]未安装', $mid));
        }

        $this->_module_init($mid);

        $ids = \Phpcmf\Service::L('input')->get('ids');
        if (!$ids) {
            $this->_json(0, dr_lang('所选内容不存在'));
        } elseif (dr_count($ids) > 9) {
            $this->_json(0, dr_lang('微信素材超过9条数据'));
        }

        $n = 1;
        $save = [
            'tid' => 'index',
            'title' => 'index',
            'content' => [],
            'media_id' => '',
            'inputtime' => SYS_TIME,
        ];
        $save['media_id'] = '';
        $save['publish_id'] = '';
        $save['article_id'] = '';
        $save['status'] = 1;
        foreach ($ids as $id) {
            $data = $this->content_model->get_data($id);
            if ($data) {
                $save['content']['title_'.$n] = $data['title'];
                $save['content']['thumb_'.$n] = $data['thumb'];
                $save['content']['author_'.$n] = $data['author'];
                $save['content']['content_'.$n] = $data['content'];
                $save['content']['description_'.$n] = $data['description'];
                $save['content']['url_'.$n] = dr_url_prefix($data['url'], $mid);
                $n++;
            }
        }

        $save['nums'] = $n;
        $save['title'] = $save['content']['title_1'];
        $save['content'] = dr_array2string($save['content']);

        \Phpcmf\Service::M()->table(weixin_wxtable('content'))->insert($save);

        $this->_json(1, '存储成功，请到微信草稿中编辑发布');
    }


    /**
     * 获取内容
     * */
    protected function _Data($id = 0) {

        $data = parent::_Data($id);
        if (!$data) {
            return [];
        }

        $value = dr_string2array($data['content']);


        return $value;
    }

    // 格式化保存数据
    protected function _Format_Data($id, $data, $old) {

        !$data[0]['title_1'] && $this->_json(0, '第一个标题不能为空', ['field' => 'title_1']);
        !$data[0]['content_1'] && $this->_json(0, '第一个内容不能为空', ['field' => 'content_1']);

        $nums = 0;

        for ($i = 1; $i<=9; $i++) {
            if ($data[0]['title_'.$i]) {
                $nums++;
            } else {
                break;
            }
        }

        $save = [
            'tid' => '',
            'nums' => $nums,
            'title' => $data[0]['title_1'],
            'content' => dr_array2string($data[0]),
            'inputtime' => SYS_TIME,
        ];

        // 每次修改媒体id重置
        $save['media_id'] = '';
        $save['publish_id'] = '';
        $save['article_id'] = '';
        $save['status'] = 1;

        return $save;
    }

    // 保存后
    protected function _Save($id = 0, $data = [], $old = [], $before = null, $after = null) {

        return parent::_Save($id, $data, $old, $before, function($id, $data, $old) {
            $content = dr_string2array($data['content']);
            for ($i = 1; $i <=9; $i++) {
                if (!$content['url_'.$i]) {
                    $content['url_'.$i] = SITE_URL.'index.php?s=weixin&c=show&id='.$id.'&p='.$i;
                }
            }
            \Phpcmf\Service::M()->table(weixin_wxtable('content'))->update($id, [
                'content' => dr_array2string($content),
            ]);
        });
    }

    //
    public function del() {
        $this->_Del(
            \Phpcmf\Service::L('Input')->get_post_ids(),
            null,
            null,
            \Phpcmf\Service::M()->dbprefix($this->init['table'])
        );
    }

    //
    public function sync_add() {

        $ids = \Phpcmf\Service::L('Input')->get_post_ids();
        if (!$ids) {
            $this->_json(0, dr_lang('所选数据不存在'));
        }

        $rt = weixin_get_access_token();
        if (!$rt['code']) {
            $this->_json(0, $rt['msg']);
        }
        $access_token = $rt['msg'];

        $rows = \Phpcmf\Service::M()->init($this->init)->where_in('id', $ids)->getAll();
        if (!$rows) {
            $this->_json(0, dr_lang('所选数据不存在'));
        }

        foreach ($rows as $t) {
            if (!$t['article_id']) {
                $rt = \Phpcmf\Service::M('Weixin', 'Weixin')->sync_content($access_token, $t);
                if (!$rt['code']) {
                    $this->_json(0, $rt['msg']);
                }
            }
        }

        $this->_json(1, '提交成功，等待平台审核');
    }

}
